<?php
/*
 * 内涵段子的热门段子 请求方式：GET 参数： c=count&p=page 参数c表示请求的条数；参数p表示请求第几页
 */
require_once 'file_php.php';
require_once 'JG_Cache.php';

$kServerFormatTxtUrl = "http://i.snssdk.com/2/essay/top/?tag=%s&page=%s&count=%s";
$kServerFormatImageUrl = "http://i.snssdk.com/2/image/top/?tag=%s&page=%s&count=%s";
$kDefaultType = "joke";
$kDefaultServerFormatUrl = $kServerFormatTxtUrl;

$kServerFormatUrls = array(
        $kDefaultType => $kServerFormatTxtUrl,
        "gif" => $kServerFormatImageUrl,
        "comic" => $kServerFormatImageUrl,
        "meng" => $kServerFormatImageUrl,
        "heavy" => $kServerFormatImageUrl
);

$kExpiration = 1 * 60; // 1min
$kCountKeyword = "count";
$kType = "type";
$kPage = "page";

$kDefaultCount = 20;
$kDefaultPage = 1;

$kDataOutputTag = "data";
$kFilterKeys = array(
        "content" => "description",
        "description" => "description",
        "thumbnail_url" => "thumbnailUrl",
        "large_url" => "largeUrl"
);

set_time_limit(0);
$count = $_GET[$kCountKeyword];
$tag = $_GET[$kType];
$page = $_GET[$kPage];

$count = (false == $count) ? $kDefaultCount : $count;
$tag = (false == $tag) ? $kDefaultType : $tag;
$page = (false == $page) ? $kDefaultPage : $page;

$kServerUrl = $kServerFormatUrls[$tag];
$kServerUrl = (false == $kServerUrl) ? $kDefaultServerFormatUrl : $kServerUrl;

$reqUrl = sprintf($kServerUrl, $tag, $page, $count);

// get cache data
$cache = new JG_Cache('cache'); // Make sure it exists and is writeable
$data = $cache->get($reqUrl, $kExpiration);
if ($data === false) {
    $data = file_php::getRemoteFile($reqUrl);
    
    $data = json_decode($data, true);
    // remove junk data
    $respArray = $data[$kDataOutputTag];
    $rearrangeArray = array();
    $current = array();
    foreach ($respArray as $itemArray) {
        foreach ($itemArray as $item => $value) {
            foreach ($kFilterKeys as $filterKey => $filterValue) {
                if (0 == strcmp($item, $filterKey)) {
                    $current[$filterValue] = $value;
                    break;
                }
            }
        }
        // add to filtered array
        $rearrangeArray[] = $current;
    }
    
    // save to cache
    $data = json_encode(
            array(
                    $kDataOutputTag => $rearrangeArray
            ));
    $cache->set($reqUrl, $data);
}
echo $data;
?>